package com.example.demo.config;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.TypeMismatchException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSON;
import com.example.demo.util.LogUtil;
import com.example.demo.util.ResultType;

/**
 * 
 * @author hulibin
 *
 * @createTime 创建时间：2017年11月29日 上午10:23:01
 * 全局异常处理
 * 
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	
    @ExceptionHandler
    public void handle(Exception e, HttpServletResponse response) throws Exception {
        ResultType result;
        if (e instanceof IllegalArgumentException || e instanceof TypeMismatchException|| e instanceof ServletRequestBindingException) {
            result = ResultType.getParamIllegal();
            LogUtil.error(e.getMessage(), e);
        }else {
            result = ResultType.getException(e.getMessage());
            LogUtil.error(e.getMessage(), e);
        }
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().print(JSON.toJSONString(result));
    }
}